package cn.iocoder.boot.controller.admin.supplier;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.http.HttpClient;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.boot.dto.DigiOldTO;
import cn.iocoder.boot.entity.ComponentStock;
import cn.iocoder.boot.job.LibraryJobHandler;
import cn.iocoder.boot.mapper.ComponentStockMapper;
import cn.iocoder.boot.service.ComponentPriceService;
import cn.iocoder.boot.service.impl.supplier.*;
import cn.iocoder.boot.utils.Base64Util;
import cn.iocoder.boot.utils.MD5Util;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;

import static cn.iocoder.boot.enums.SupplierCodeEnum.JBCHIP;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "京北通宇商城接口")
@RestController
@RequestMapping("/jbchip")
@Slf4j
public class JBCHIPController {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(JBCHIPController.class);
    private static final HttpClient client = HttpClient.newHttpClient();
    @Resource
    private ComponentStockMapper componentStockMapper;

    @Resource
    private ComponentPriceService priceService;

    @Resource
    private JBCHIPServiceImpl jbchipService;

    @Resource
    private ICEasyServiceImpl icEasyService;

    @Resource
    private MouserServiceImpl mouserService;

    @Resource
    private ElementServiceImpl elementService;

    @Resource
    private YunhanServiceImpl yunhanServiceImpl;

    @Resource
    private SHTServiceImpl shtServiceImpl;

    @Resource
    private DigikeyServiceImpl digikeyService;

    @Resource
    private TMEServiceImpl tmeService;

    @Resource
    private LibraryJobHandler libraryJobHandler;

    private static final String DIGIKEY_API_URL = "https://api.digikey.com/products/v4/search/keyword";
    private static final String CLIENT_ID = "lnGfrAAGJZMWdzRYe7eJTEn5tgEl0eKc";
    private static final String CUSTOMER_ID = "10183130";

    //初始化数据
    @PermitAll
    @GetMapping("/init")
    @Operation(summary = "初始化数据")
    public CommonResult<String> init() {
        jbchipService.init();




        return success("成功");
    }


    //日更
    @PermitAll
    @GetMapping("/dayUpdate")
    @Operation(summary = "日更")
    //感觉没用
    public CommonResult<String> dayUpdate(){


        LocalDateTime now = LocalDateTime.now();
        String startTime = now.withHour(0).withMinute(0).withSecond(0)
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String endTime = now.withHour(23).withMinute(59).withSecond(59)
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        List<ComponentStock> componentStockList=new ArrayList<>();

        String preString = "{\n" +
                "\"charset\": \"utf-8\",\n" +
                "\"biz_content\": \"{\\\"page_no\\\":1,\\\"page_size\\\":500,\\\"start_time\\\":\\\"" + startTime +
                "\\\",\\\"end_time\\\":\\\"" + endTime + "\\\"}\",\n" +
                "\"partner_id\": \"jbchip\",\n" +
                "\"method\": \"jbchip.api.goods.list\",\n" +
                "\"time_stamp\": \"2021-09-01 09:22:05\",\n" +
                "\"format\": \"JSON\",\n" +
                "\"channel_type\": \"5900\",\n" +
                "\"app_id\": \"ty885950\",\n" +
                "\"version\": \"1.0\",\n" +
                "\"key\": \"S0BpdFwqaUYh0oHsxBb2NI\"\n" +
                "}\n";

        try {
            String result = sortAndJoinJsonKeyValues(preString);
            String s = MD5Util.md5(result);
            String encode = Base64Util.encode(s);
            System.out.println(encode);



            String apiUrl = "https://www.jbchip.com/gateway.action";

            // 构建请求JSON对象
            JSONObject requestBody = new JSONObject();
            requestBody.set("charset", "utf-8");
            requestBody.set("biz_content",
                    "{\"page_no\":1,\"page_size\":500,\"start_time\":\"" + startTime + "\",\"end_time\":\"" + endTime + "\"}");
            requestBody.set("partner_id", "jbchip");
            requestBody.set("method", "jbchip.api.goods.list");
            requestBody.set("time_stamp", "2021-09-01 09:22:05");
            requestBody.set("format", "JSON");
            requestBody.set("sign", encode);
            requestBody.set("channel_type", "5900");
            requestBody.set("app_id", "ty885950");
            requestBody.set("version", "1.0");
            requestBody.set("sign_type", "MD5");

            HttpResponse response = HttpRequest.post(apiUrl)
                    .contentType("application/json") // 设置Content-Type
                    .body(requestBody.toString())     // 设置请求体
                    .timeout(5000)                   // 设置超时时间
                    .execute();

            if (response.isOk()) {
                String responseBody = response.body();
                System.out.println("API响应: " + responseBody);
                JSONObject jsonResponse = JSONUtil.parseObj(responseBody);
                // 检查返回码
                if (jsonResponse.getInt("return_code") != 1000) {
                    throw new RuntimeException("API请求失败: " + jsonResponse.getStr("return_msg"));
                }

                // 获取商品列表
                JSONObject returnData = jsonResponse.getJSONObject("return_data");
                JSONArray goodsList = returnData.getJSONArray("goods_list");

                // 遍历商品列表并封装到ComponentStock
                for (int i = 0; i < goodsList.size(); i++) {
                    JSONObject goods = goodsList.getJSONObject(i);

                    ComponentStock stock = new ComponentStock(
                            goods.getStr("goods_url"),        // picUrl
                            goods.getStr("part_no"),          // model
                            goods.getStr("category"),         // type
                            goods.getStr("brand_name"),       // brand
                            goods.getStr("description"),                          // specifications
//                            goods.getStr("pack"),            // encapsulation
                            null,                             // attribute (无对应字段)
                            1,                               // stockType (固定值1)
                            JBCHIP.getCode(),                              // supplierCode (固定传1)

                            goods.getStr("goods_package")
                    );

                    componentStockList.add(stock);
                }
                componentStockMapper.insert(componentStockList);



            } else {
                System.err.println("请求失败，状态码: " + response.getStatus());
                System.err.println("错误信息: " + response.body());
            }

        } catch (Exception e) {
            logger.info("失败: " + e.getMessage());
            e.printStackTrace();
        }

        return success("成功");
    }


    public static String sortAndJoinJsonKeyValues(String jsonString) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(jsonString);

        List<String> keyValuePairs = new ArrayList<>();

        // 遍历 JSON 节点，构建键值对列表
        for (Map.Entry<String, JsonNode> entry : (Iterable<Map.Entry<String, JsonNode>>) () -> jsonNode.fields()) {
            String key = entry.getKey();
            String value = entry.getValue().isTextual() ? entry.getValue().asText() : entry.getValue().toString();
            keyValuePairs.add(key + "=" + value);
        }

        // 对键值对进行排序
        Collections.sort(keyValuePairs);

        // 用 "&" 连接所有键值对
        return String.join("&", keyValuePairs);
    }


    @PermitAll
    @GetMapping("/test")

    public CommonResult<String> test() throws Exception {


        libraryJobHandler.execute("test");
         return success("成功");

    }

    @PermitAll
    @PostMapping("/GetQuote")
    @Operation(summary = "得捷老接口")
    public String getQuote(@RequestBody  DigiOldTO query) throws Exception {
        try {
            // 准备请求头
            String jsonBody = String.format("{\"Keywords\": \"%s\"}", query.getKeyWord());

            String url = String.format("https://api.digikey.com/products/v4/search/keyword");

            // 创建 HttpRequest 实例
            java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Content-Type", "application/json") // 再次确认 Content-Type
                    .header("X-DIGIKEY-Client-Id", "lnGfrAAGJZMWdzRYe7eJTEn5tgEl0eKc")
                    .header("X-DIGIKEY-Locale-Language", "zhs")
                    .header("X-DIGIKEY-Locale-Currency", query.getCurrency())
                    .header("X-DIGIKEY-Locale-Site", "CN")
                    .header("X-DIGIKEY-Customer-Id", "10183130")
                    .header("Authorization", "Bearer " + query.getToken())
                    .POST(java.net.http.HttpRequest.BodyPublishers.ofString(jsonBody))
                    .build();

            java.net.http.HttpResponse<String> response = client.send(request, java.net.http.HttpResponse.BodyHandlers.ofString());

            String responseBody = response.body();
            log.info("请求得捷关键字成功", responseBody);
            // 返回响应体
            return responseBody;
        } catch (Exception ex) {
            System.out.println("请求得捷关键字错误，物料为: " + query.getKeyWord());
            throw new Exception("Error in GetQuote", ex);
        }
    }



    @PermitAll
    @PostMapping("/GetProductDetails")
    @Operation(summary = "得捷老接口查价格")
    public String GetProductDetails(@RequestBody  DigiOldTO query) throws Exception {
        try {
            String url = String.format("https://api.digikey.com/products/v4/search/%s/productdetails", query.getKeyWord());

            // 创建 HttpRequest 实例
            java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("X-DIGIKEY-Client-Id", "lnGfrAAGJZMWdzRYe7eJTEn5tgEl0eKc")
                    .header("X-DIGIKEY-Locale-Language", "zhs")
                    .header("X-DIGIKEY-Locale-Currency", query.getCurrency())
                    .header("X-DIGIKEY-Locale-Site", "CN")
                    .header("X-DIGIKEY-Customer-Id", "10183130")
                    .header("Authorization", "Bearer " + query.getToken())
                    .build();

            // 发送请求
            java.net.http.HttpResponse<String> response = client.send(request, java.net.http.HttpResponse.BodyHandlers.ofString());

            String responseBody = response.body();
            log.info("请求得捷价格成功", responseBody);
            // 返回响应体
            return responseBody;
        } catch (Exception ex) {
            System.out.println("请求得捷价格错误，物料为: " + query.getKeyWord());
            throw new Exception("Error in GetQuote", ex);
        }
    }
}
